﻿using Aspose.Words;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.AccessControl;
using System.Web;
using System.Web.Hosting;
using System.Web.Mvc;

namespace PMS.Controllers
{
    public class FileController : Controller
    {
        string path = @"C:\管理系统附件\";
        public ActionResult AddFile()
        {
            return View();
        }
        [HttpPost]
        public JsonResult GetFiles(string guid)
        {
            List<BD_Files> list = BLLSession.Current.BD_FilesBLL.GetListBy(u => u.GUID == guid && u.isDelete == "0");
            return Json(list);
        }
        [HttpPost]
        public JsonResult Upload(string guid)
        {
            if (System.Web.HttpContext.Current.Request.Files.Count > 0)
            {
                string today_path = path + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
                if (!Directory.Exists(today_path))
                {
                    try
                    {
                        Directory.CreateDirectory(today_path);
                    }
                    catch (Exception ex)
                    {
                        return Json(new { res = "error", msg = ex.Message });
                    }
                }
                try
                {
                    HttpPostedFile file = System.Web.HttpContext.Current.Request.Files[0];
                    BD_Files info = new BD_Files();
                    info.FileAllName = file.FileName;
                    info.SysName = DateTime.Now.ToFileTime().ToString() + Guid.NewGuid().ToString("N");
                    info.Suffix = Path.GetExtension(file.FileName);
                    info.Size = file.ContentLength;
                    info.AddName = OperateContext.sessUserInfo.Name;
                    info.AddTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    info.GUID = guid;
                    info.isDelete = "0";
                    info.url = today_path + info.SysName;
                    file.SaveAs(info.url);
                    BD_Files newinfo = BLLSession.Current.BD_FilesBLL.AddReturnModel(info);
                    return Json(new { res = "success", info = newinfo });
                }
                catch (Exception ex)
                {
                    return Json(new { res = "error", msg = ex.Message });
                }
            }
            else
            {
                return Json(new { res = "error", msg = "服务器后台未接收到文件" });
            }
        }
        [HttpPost]
        public void Download()
        {
            int id = int.Parse(Request.Form["ID"]);
            BD_Files info = BLLSession.Current.BD_FilesBLL.GetListBy(u => u.ID == id).FirstOrDefault();
            FileStream fs = new FileStream(info.url, FileMode.Open);
            byte[] bytes = new byte[(int)fs.Length];
            fs.Read(bytes, 0, bytes.Length);
            fs.Close();
            Response.ContentType = "application/octet-stream";
            Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(info.FileAllName, System.Text.Encoding.UTF8));
            Response.BinaryWrite(bytes);
            Response.Flush();
            Response.End();
        }
        [HttpPost]
        public void Delete()
        {
            int id = int.Parse(Request.Form["ID"]);
            BD_Files info = BLLSession.Current.BD_FilesBLL.GetListBy(u => u.ID == id).FirstOrDefault();
            info.isDelete = "1";
            BLLSession.Current.BD_FilesBLL.ModifyAllModel(info);
            Response.Write(JsonHelper.toDefaultMsg(true));
        }

        [HttpPost]
        public void ViewPDF()
        {
            int id = int.Parse(Request.Form["ID"]);
            BD_Files info = BLLSession.Current.BD_FilesBLL.GetListBy(u => u.ID == id).FirstOrDefault();
            string rootPath = HttpRuntime.AppDomainAppPath;
            string viewPath = string.Format("{0}ViewFiles\\{1}{2}", rootPath, info.SysName, info.Suffix);
            System.IO.File.Copy(info.url, viewPath, true);
            Response.Write(JsonHelper.toJson(new { state = "success", msg = info.SysName + info.Suffix }));
        }
        [HttpPost]
        public void ViewWord()
        {
            int id = int.Parse(Request.Form["ID"]);
            BD_Files info = BLLSession.Current.BD_FilesBLL.GetListBy(u => u.ID == id).FirstOrDefault();
            string rootPath = HttpRuntime.AppDomainAppPath;
            string viewPath = string.Format("{0}ViewFiles\\{1}{2}", rootPath, info.SysName, ".pdf");
            //System.IO.File.Copy(info.url, viewPath, true);
            Word2PDF(info.url, viewPath);
            Response.Write(JsonHelper.toJson(new { state = "success", msg = info.SysName + ".pdf" }));
        }
        
        [HttpPost]
        public void ViewMP4()
        {
            int id = int.Parse(Request.Form["ID"]);
            BD_Files info = BLLSession.Current.BD_FilesBLL.GetListBy(u => u.ID == id).FirstOrDefault();
            string rootPath = HttpRuntime.AppDomainAppPath;
            string viewPath = string.Format("{0}ViewFiles\\{1}{2}", rootPath, info.SysName, info.Suffix);
            System.IO.File.Copy(info.url, viewPath, true);
            Response.Write(JsonHelper.toJson(new { state = "success", msg = info.SysName + info.Suffix }));
        }
        private bool Word2PDF(string soursePath, string savePath)
        {
            try
            {
                if (System.IO.File.Exists(soursePath))
                {
                    Document doc = new Document(soursePath);
                    doc.Save(savePath);

                }
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}
